package com.github.pig.goods.bussiness.product.controller;

import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pig.common.constant.CommonConstant;
import com.github.pig.common.util.Query;
import com.github.pig.common.util.R;
import com.github.pig.common.util.UserUtils;
import com.github.pig.common.web.BaseController;
import com.github.pig.goods.bussiness.product.entity.TAgentProduct;
import com.github.pig.goods.bussiness.product.entity.TProduct;
import com.github.pig.goods.bussiness.product.entity.TProductPrice;
import com.github.pig.goods.bussiness.product.entity.ToProduct;
import com.github.pig.goods.bussiness.product.service.ITAgentProductService;
import com.github.pig.goods.bussiness.product.service.ITAgentService;
import com.github.pig.goods.bussiness.product.service.ITProductPriceService;
import com.github.pig.goods.bussiness.product.service.ITProductService;
import com.github.pig.goods.common.util.CreateQRForProductAndSN;
import com.github.pig.goods.common.util.QRCodeKit;
import com.github.pig.goods.common.util.UploadFile;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * <p>
 * 产品表 前端控制器
 * </p>
 *
 * @author Carlos123
 * @since 2018-08-23
 */
@RestController
@Slf4j
@RequestMapping("/tProduct")
@Api(value = "TProductController", description = "产品表")
public class TProductController extends BaseController{


    @Autowired
    private ITProductService tProductService;

    @Autowired
    private ITAgentProductService tAgentProductService;

    @Autowired
    private ITAgentService tAgentService;

    @Autowired
    private ITProductPriceService tProductPriceService;

/**
 * 通过ID查询
 *
 * @param id ID
 * @return TProduct
 */
@GetMapping("/{id}")
@ApiOperation(value = "  按id查询", httpMethod = "GET", notes = "  按id查询")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
public R<TProduct> get(@PathVariable String id){
    return new R<>(tProductService.getProductById(id));
}


/**
* 分页查询信息
*
* @param params 分页对象
* @return 分页对象
*/
@RequestMapping("/page")
@ApiOperation(value = "分页查询 参数为TProduct表中的属性",httpMethod = "GET",  notes = "TProduct列表方法")
@ApiImplicitParam(name = "查询参数", value = "TProduct参数", required = true, dataType = "Map", paramType = "path")
public Page page(@RequestParam Map<String, Object> params){
    params.put(CommonConstant.DEL_FLAG,CommonConstant.STATUS_NORMAL);
    Page<ToProduct> list = tProductService.selectWithProductPage(new Query<>(params));

    for (ToProduct p:list.getRecords()) {
        List<TProductPrice> pp= tProductPriceService.selectList(Condition.create().eq("product_id",p.getId()).orderBy("price",false));
        p.setPriceList(pp);
    }
    return list;
}

/**
 * 添加
 * @param  tProduct 实体
 * @return success/false
 */
@PostMapping
@ApiOperation(value = "新增实体 参数为tProduct实体", notes = "TProduct新增方法")
@ApiImplicitParam(name = "tProduct", value = "TProduct实体", required = true, dataType = "TProduct")
public R<Boolean> add(@RequestBody  TProduct tProduct){
    if (tProduct.getSameStyleNum()!=null&&tProduct.getSameStyleNum()!=""){
        TProduct p = tProductService.selectOne(Condition.create().eq("same_style_num",tProduct.getSameStyleNum()));
        if (p!=null){
            return new R<>(false,"产品已在系统中！");
        }else{
            tProduct.setCreateTime(new Date()).setCreator(UserUtils.getUser());
            return new R<>(tProductService.insert(tProduct));
        }
    }else {
            return new R<>(false,"参数错误，无SameStyleNum！");
    }

}


    /**
     * 添加
     * @param  tProductList 实体列表
     * @return success/false
     */
    @PostMapping("/addList")
    @ApiOperation(value = "批量新增实体 参数为list<tProduct>实体", notes = "TProduct新增方法")
    @ApiImplicitParam(name = "tProduct", value = "TProduct实体", required = false, dataType = "list")
    public R<Boolean> addList(@RequestBody List<TProduct> tProductList){
        tProductList.forEach(o-> {
            if (o.getSameStyleNum() != null&&o.getSameStyleNum()!="") {
                TProduct p = tProductService.selectOne(Condition.create().eq("same_style_num",o.getSameStyleNum()));
                if (p!=null){
                    tProductList.remove(o);
                }
                o.setCreateTime(new Date()).setCreator(UserUtils.getUser());
            }else {
                    tProductList.remove(o);
            }

        });
        return new R<>(tProductService.insertBatch(tProductList),"插入成功，未成功的无[same_style_num]参数");
    }




    /**
     * 批量上架 1：上架 0：下架
     * @param  idList ids
     * @return success/false
     */
    @PostMapping("/batchUpProduct")
    @ApiOperation(value = "批量上架产品 参数为list<string>实体", notes = "TProduct新增方法")
    @ApiImplicitParam(name = "字符串id", value = "ids", required = false, dataType = "list")
    public R<Boolean> upProductList(@RequestBody List<String> idList){
        List<TProduct> productList = tProductService.selectBatchIds(idList);
        //批量上架
        productList.forEach(o->o.setStatus("1"));
        return new R<>( tProductService.updateAllColumnBatchById(productList));
    }

    /**
     * 批量上架 1：上架 0：下架
     * @param  idList ids
     * @return success/false
     */
    @PostMapping("/batchDownProduct")
    @ApiOperation(value = "批量下架产品 参数为list<string>实体", notes = "批量下架")
    @ApiImplicitParam(name = "字符串id", value = "ids", required = false, dataType = "list")
    public R<Boolean> downProductList(@RequestBody List<String> idList){
        List<TProduct> productList = tProductService.selectBatchIds(idList);
        //批量上架
        productList.forEach(o->o.setStatus("0"));
        return new R<>( tProductService.updateAllColumnBatchById(productList));
    }


@DeleteMapping("/{id}")
@ApiOperation(value = "按id删除", notes = "TProduct删除")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<Boolean> delete(@PathVariable String id){return new R<>(tProductService.deleteById(id));}






@GetMapping("/{id}/{sn}/getQRCode")
@ApiOperation(value = "获取商品二维码", notes = "获取商品二维码")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "long", paramType = "path")
public R<String> getQRCode(@PathVariable String id,@PathVariable String sn,HttpServletRequest request) throws Exception {
    TProduct product = tProductService.selectById(id);
    if (product == null){
        return new R<>(null,"无效产品");
    }else{
        URL QRUrl;
       TAgentProduct ap= tAgentProductService.selectOne(Condition.create().eq("product_id",product.getId()));
       if (ap!=null){
           log.info("TAgentProduct ap:"+ap.getQr());

           if(ap.getQr()!=null&&!"".equals(ap.getQr())){
                return  new R<>(ap.getQr());
           }else{
               QRUrl = CreateQRForProductAndSN.getQRCode(request,product.getSameStyleNum(),id,sn);
               ap.setQr(QRUrl.toString().substring(0,QRUrl.toString().indexOf("?")));
               tAgentProductService.updateById(ap);
               log.info("ok");
               return new R<>(QRUrl.toString().substring(0,QRUrl.toString().indexOf("?")));
           }
       }else{
           return new R<>(null,"改产品无代理商");
       }

    }

}

    public static void main(String[] args) throws MalformedURLException {
        String  url = "http://kyb-pic-server-1257189861.cos.ap-guangzhou.myqcloud.com/QRCode/00111111111111111.png?sign=q-sign-algorithm%3Dsha1%26q-ak%3DAKIDc5PhmePkxwlMjuFb6MNGxSkphLm0ipPn%26q-sign-time%3D1565964439%3B1565967439%26q-key-time%3D1565964439%3B1565967439%26q-header-list%3D%26q-url-param-list%3D%26q-signature%3D0b49ea08340253213319c6d285fe74e7337ca758";
        URL u = new URL(url);
        System.out.println(u.toString().substring(0,u.toString().indexOf("?")));
    }



/**
 * 编辑
 * @param  tProduct 实体
 * @return success/false
 */
@PutMapping("/update")
@ApiOperation(value = "修改 参数为tProduct实体", notes = "TProduct修改")
@ApiImplicitParam(name = "tProduct", value = "TProduct实体", required = true, dataType = "TProduct", paramType = "path")
public R<Boolean> edit(@RequestBody TProduct tProduct){
    tProduct.setUpdateTime(new Date());
    return new R<>(tProductService.updateById(tProduct));
}



    /**
     * 上传文件
     * 访问路径：https://kyb-pic-server-1257189861.cos.ap-guangzhou.myqcloud.com
     * @param file 资源
     * @return PutObjectResult
     */
    @PostMapping("/upload" )
    @ApiOperation(value = "上传文件", notes = "")
    public R upload(@RequestParam("file" ) MultipartFile file, HttpServletRequest request) {
        String uri  =null;
        File newFile = new File(file.getOriginalFilename());

        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), newFile);
            URL url= UploadFile.picCOS(newFile,null,null);
            log.info("文件上传成功！路径为：{}",url.toString());
            newFile.delete();

            //第二种拼接方法 腾讯cos 带？后面的参数图片无显示bug
            uri=url.getProtocol()+"://"+url.getHost()+url.getPath();

            //StringUtils.substringBefore(url.toString(),"?")
            return new R<>(uri);
        }catch (Exception e){
            e.printStackTrace();
        }
            return new R();
    }


}
